﻿namespace MEFAddin
{
    using System.Collections.Generic;
    using System.Linq;
    using MEFAddin.Controllers;
    using MEFAddin.Interfaces;

    /// <summary>
    /// The anscestor for all controllers.
    /// </summary>
    public class MEFController : AddInController
    {
        private List<IAddInCommand> _Commands;

        /// <summary>
        /// Initializes a new instance of the <see cref="MEFController"/> class.
        /// </summary>
        public MEFController()
        {
            this._Commands = new List<IAddInCommand>();
        }

        /// <summary>
        /// Adds the MEF command.
        /// </summary>
        /// <param name="command">The command.</param>
        internal void AddMEFCommand(IAddInCommand command)
        {
            this._Commands.Add(command);
        }

        /// <summary>
        /// Internals the exec.
        /// </summary>
        /// <param name="CmdName">Name of the CMD.</param>
        /// <param name="ExecuteOption">The execute option.</param>
        /// <param name="VariantIn">The variant in.</param>
        /// <param name="VariantOut">The variant out.</param>
        /// <param name="Handled">if set to <c>true</c> [handled].</param>
        protected override void InternalExec(string CmdName, EnvDTE.vsCommandExecOption ExecuteOption, ref object VariantIn, ref object VariantOut, ref bool Handled)
        {
            var cmd = FindCommand(CmdName);
            if (cmd != null)
            {
                cmd.Execute();
                Handled = true;
            }
            else
            {
                Handled = false;
            }
        }

        /// <summary>
        /// Finds the command.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        private IAddInCommand FindCommand(string name)
        {
            return this._Commands.Where(cmd => cmd.CommandInstance.Name == name).FirstOrDefault();
        }

    }
}
